package com.zscat.mallplus.controller.order;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.controller.single.ApiBaseAction;
import com.zscat.mallplus.entity.vo.CartParam;
import com.zscat.mallplus.entity.vo.oms.*;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.exception.ApiMallPlusException;
import com.zscat.mallplus.oms.entity.OmsCartItem;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.entity.OmsPayments;
import com.zscat.mallplus.oms.vo.OrderListInfo;
import com.zscat.mallplus.oms.vo.OrderParam;
import com.zscat.mallplus.service.oms.service.IOmsCartItemService;
import com.zscat.mallplus.service.oms.service.IOmsOrderItemService;
import com.zscat.mallplus.service.oms.service.IOmsOrderService;
import com.zscat.mallplus.service.oms.service.IOmsPaymentsService;
import com.zscat.mallplus.service.sms.service.ISmsCouponService;
import com.zscat.mallplus.service.ums.service.IUmsMemberService;
import com.zscat.mallplus.sms.entity.SmsCoupon;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.mapper.UmsMemberMapper;
import com.zscat.mallplus.util.PayDigestUtil;
import com.zscat.mallplus.util.PayUtil;
import com.zscat.mallplus.util.ResponseObject;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import com.zscat.mallplus.vo.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Auther: shenzhuan
 * @Date: 2019/4/2 15:02
 * @Description:
 */
@Slf4j
@RestController
@Api(tags = "OmsController", description = "订单管理系统")
@RequestMapping("/api/orderV1")
public class OrderController extends ApiBaseAction {

    // 物流信息缓存间隔暂定3个小时
    private static final Long maxCacheTime = 1000 * 60 * 60 * 3L;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private IOmsPaymentsService paymentsService;
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private IOmsCartItemService cartItemService;

    @Resource
    private ISmsCouponService couponService;

//    /**
//     * 立即购买/快速下单
//     * 添加商品到购物车便于下单
//     *
//     * @param cartParam
//     * @return
//     */
//    @IgnoreAuth
//    @RequestMapping(value = "/goBuy")
//    @ResponseBody
//    public Object goBuy(CartParam cartParam) {
//        try {
//            // 校验用户
//            if (ValidatorUtils.empty(cartParam.getMemberId())) {
//                return new CommonResult().fail(100);
//            }
//            // 校验数量
//            if (ValidatorUtils.empty(cartParam.getTotal())) {
//                cartParam.setTotal(1);
//            }
//            orderService.doGoBuy(cartParam);
//            return new CommonResult().fail(100);
//        } catch (ApiMallPlusException e) {
//            return new CommonResult().failed(e.getMessage());
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new CommonResult().failed("系统错误，请稍后再试！");
//        }
//    }

    @Autowired
    private IUmsMemberService memberService;

    /**
     * 立即购买/快速下单-跳转到确认订单页面
     * type:1 商品详情 2 勾选购物车 3全部购物车的商品
     *
     * @param subPreOrderParam
     * @return
     */
//    @IgnoreAuth
    @ResponseBody
    @GetMapping("/submitPreview")
    public CommonResult submitPreview(SubPreOrderParam subPreOrderParam) {
        UmsMember umsMember = memberService.getNewCurrentMember();
        subPreOrderParam.setMemberId(umsMember.getId());
        try {
            if (subPreOrderParam.getType().equals("1")) {
                ConfirmOrderInfo result = orderService.getSubmitPreviewInfo(subPreOrderParam);
                return new CommonResult().success(result);
            } else {
                ConfirmOrderInfo result = orderService.getSubmitPreviewInfoV1(subPreOrderParam);
                return new CommonResult().success(result);
            }
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 确认订单选择优惠券
     * 计算优惠券价格
     */
    @ResponseBody
    @GetMapping("/selectCoupon")
    public CommonResult selectCoupon(String cartIds, Long skuId, Long goodsId, Integer total, String type, Long couponId) {
        UmsMember umsMember = memberService.getNewCurrentMember();
        Long memberId = umsMember.getId();
        try {
            if (type.equals("1")) {
                // 商品详情
                OmsCartItem omsCartItem = orderService.saveOmsCartItemInfo(skuId, goodsId, total, memberId);
                cartIds = omsCartItem.getId() + "";
            }
            // 校验参数
            if (org.apache.commons.lang.StringUtils.isBlank(cartIds)) {
                throw new ApiMallPlusException("cartIds参数为空");
            }
            if (couponId == null) {
                throw new ApiMallPlusException("couponId参数为空");
            }
            String[] ids1 = cartIds.split(",");
            List<Long> resultList = new ArrayList<>(ids1.length);
            for (String s : ids1) {
                resultList.add(Long.valueOf(s));
            }
            List<OmsCartItem> cartPromotionItemList = cartItemService.listPromotion(memberId, resultList);
            if (cartPromotionItemList == null || cartPromotionItemList.size() < 1) {
                throw new ApiMallPlusException("没有下单的商品！");
            }
            // 计算优惠券
            SmsCoupon smsCoupon = couponService.getById(couponId);
            if (smsCoupon == null) {
                throw new ApiMallPlusException("优惠券不存在");
            }
            // 判断优惠券是否过期了
            if (!this.belongCalendar(new Date(), smsCoupon.getStartTime(), smsCoupon.getEndTime())) {
                throw new ApiMallPlusException("优惠券过期了");
            }
            BigDecimal coupon = orderService.calculationCoupon(cartPromotionItemList, couponId, memberId);
            if (type.equals("1")) {
                // 删除购物车里的临时商品
                cartItemService.delete(memberId, resultList);
            }
            return new CommonResult().success(coupon);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成订单/立即支付
     */
    @RequestMapping(value = "/generateOrder")
    @ResponseBody
    public CommonResult generateOrder(GenerateOrderParam orderParam) {
        try {
            // 获取当前的用户
            UmsMember umsMember = memberService.getNewCurrentMember();
            Long memberId = umsMember.getId();
            orderParam.setMemberId(memberId);
            if (orderParam.getOrderId() != null) {
                // 立即付款
                OmsOrder omsOrder = orderService.getById(orderParam.getOrderId());
                OrderPayPageInfo result = new OrderPayPageInfo();
                result.setTotalOrderSn(omsOrder.getOrderSn());
                result.setPaymentList(paymentsService.list(new QueryWrapper<OmsPayments>().eq("status", 1)));
                result.setOrderSubmitTime(omsOrder.getCreateTime().getTime());
                return new CommonResult().success(result);
            }
            // 购物车id集合
            String cartIds = orderParam.getCartIds();
            if (orderParam.getType().equals("1")) { // 商品详情
                // 添加到购物车中
                OmsCartItem omsCartItem = orderService.saveOmsCartItemInfo(orderParam.getSkuId(), orderParam.getGoodsId(), orderParam.getTotal(), orderParam.getMemberId());
                log.info("添加到购物车中：" + omsCartItem.toString());
                cartIds = omsCartItem.getId() + "";
                orderParam.setCartIds(cartIds);
            }
            // 校验参数
            if (org.apache.commons.lang.StringUtils.isBlank(cartIds)) {
                throw new ApiMallPlusException("cartIds参数为空");
            }

            if (orderParam.getType().equals("1")) {// 商品详情
                OrderPayPageInfo result = orderService.generateOrderV2(orderParam);
                return new CommonResult().success(result);
            } else {
                OrderPayPageInfo result1 = orderService.generateOrderV3(orderParam);
                return new CommonResult().success(result1);
            }
        } catch (ApiMallPlusException e) {
            e.printStackTrace();
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 订单支付/立即付款
     * 订单号、支付类型
     */
    @IgnoreAuth
    @RequestMapping(value = "/payOrder")
    @ResponseBody
    public CommonResult payOrder(String orderNo, Integer payType) {
        try {

            OmsOrder orderInfo = new OmsOrder();
            orderInfo.setPayType(payType);
            orderInfo.setStatus(2);               // 已支付
            orderInfo.setConfirmStatus(1);       // 已支付
            orderInfo.setPaymentTime(new Date());// 支付时间
            orderService.updateById(orderInfo);

            orderService.update(orderInfo, new QueryWrapper<OmsOrder>().eq("total_order_sn", orderNo).or().eq("order_sn", orderNo));
            // 支付成功
            System.out.println("支付成功");
            return new CommonResult().success();
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    /**
     * 获取订单详情
     *
     * @param id
     * @return
     */
    @IgnoreAuth
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public Object detail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        try {
            OrderDetailResult orderDetailResult = orderService.getOrderDetailResult(id);
            return new CommonResult().success(orderDetailResult);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    /**
     * 查询订单列表
     */
    @IgnoreAuth
    @GetMapping(value = "/searchlist")
    public Object orderList(String keyWord, Integer status, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                            @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex) {
        try {
            UmsMember umsMember = memberService.getNewCurrentMember();
            Long memberId = umsMember.getId();
            PageInfo<OrderListInfo> page = orderService.getOrderList(keyWord, memberId, status, pageIndex, pageSize);
            return new CommonResult().success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed(e.getMessage());
        }
    }

    /**
     * 取消订单
     * 等待付款-解锁库存
     *
     * @param orderId
     * @return
     */
    @IgnoreAuth
    @RequestMapping(value = "/closeOrder", method = RequestMethod.POST)
    public Object closeOrder(Long orderId) {
        try {
            if (ValidatorUtils.empty(orderId)) {
                return new CommonResult().paramFailed("订单id不能为空！");
            }
            OmsOrder newE = orderService.getById(orderId);
//            if (newE.getStatus() != OrderStatus.INIT.getValue()) {
//                return new CommonResult().paramFailed("订单已支付，不能关闭！");
//            }
            if (orderService.closeOrder(newE)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @return
     */
    @IgnoreAuth
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
    public Object deleteOrder(Long orderId) {
        try {
            if (ValidatorUtils.empty(orderId)) {
                return new CommonResult().paramFailed("订单id is empty");
            }
            OmsOrder newE = orderService.getById(orderId);
            if (orderService.deleteOrder(newE)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

}
